package com.insurance.common.utils;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;


/**
 * @author Daniel
 */

/**
 * 加密解密类
 */
public class Decrypt {
    private static final Logger logger = LoggerFactory.getLogger(Decrypt.class);
    private static final String defaultCharset = "UTF-8";
    private static final String KEY_AES = "AES";
    private static final String KEY_MD5 = "MD5";
    private static MessageDigest md5Digest;

    static {
        try {
            md5Digest = MessageDigest.getInstance(KEY_MD5);
        } catch (NoSuchAlgorithmException e) {

        }
    }

    /**
     * 加密
     *
     * @param data
     *            需要加密的内容
     * @param key
     *            加密密码
     * @return
     */
    public static String encrypt(String data, String key) {

        return doAES(data, key, Cipher.ENCRYPT_MODE);
    }

    /**
     * 解密
     *
     * @param data
     *            待解密内容
     * @param key
     *            解密密钥
     * @return
     */
    public static String decrypt(String data, String key) {

        return doAES(data, key, Cipher.DECRYPT_MODE);
    }

    /**
     * 加解密
     *
     * @param data
     * @param key
     * @param mode
     * @return
     */
    private static String doAES(String data, String key, int mode) {

        try {
            if (StringUtils.isBlank(data) || StringUtils.isBlank(key)) {
                return null;
            }

            boolean encrypt = mode == Cipher.ENCRYPT_MODE;
            byte[] content;
            if (encrypt) {
                content = data.getBytes(defaultCharset);

            } else {
                content = Base64.decodeBase64(data.getBytes(defaultCharset));

            }
            // 创建密钥
            SecretKeySpec keySpec = new SecretKeySpec(md5Digest.digest(key.getBytes(defaultCharset)), KEY_AES);
            // 创建密码器
            Cipher cipher = Cipher.getInstance(KEY_AES);
            // 初始化
            cipher.init(mode, keySpec);

            byte[] result = cipher.doFinal(content);

            if (encrypt) {
                return new String(Base64.encodeBase64(result));

            } else {
                return new String(result, defaultCharset);

            }
        } catch (Exception e) {
            logger.error("AES密文处理异常" + e.getMessage(), e);

        }
        return null;
    }

    public static String decrypt(String data,byte[] key){  //对string进行BASE64Encoder转换
        try {
            sun.misc.BASE64Decoder base64en = new sun.misc.BASE64Decoder();
            byte[] bt = decrypt(base64en.decodeBuffer(data), key);
            String strs = new String(bt);
            return strs;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    private static byte[] decrypt(byte[] src,byte[] key) throws Exception {
        // DES算法要求有一个可信任的随机数源
        SecureRandom random = new SecureRandom();
        // 创建一个DESKeySpec对象
        DESKeySpec desKey = new DESKeySpec(key);
        // 创建一个密匙工厂
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        // 将DESKeySpec对象转换成SecretKey对象
        SecretKey securekey = keyFactory.generateSecret(desKey);
        // Cipher对象实际完成解密操作
        Cipher cipher = Cipher.getInstance("DES");
        // 用密匙初始化Cipher对象
        cipher.init(Cipher.DECRYPT_MODE, securekey, random);
        // 真正开始解密操作
        return cipher.doFinal(src);
    }

    public static void main(String[] args) {
        //String data = "12346sdfkasfaljfalkadsfjalfjaafkjakfdjasdf";
        String data = "aC2viWIX1kmyfXlZNEgKCtR2Cxlxs000UR59npBGi5ZXoxvt5yNH+NtWH/UfMKgu";
        String key = "axlifeTest";
        System.out.println("报文密文" + encrypt(data,key));
        System.out.println("报文解密" + decrypt(data,key));
    }

    public static String getSha1(String str) {

        char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                'a', 'b', 'c', 'd', 'e', 'f' };
        try {
            MessageDigest mdTemp = MessageDigest.getInstance("SHA1");
            mdTemp.update(str.getBytes("UTF-8"));
            byte[] md = mdTemp.digest();
            int j = md.length;
            char buf[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                buf[k++] = hexDigits[byte0 >>> 4 & 0xf];
                buf[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(buf);
        } catch (Exception e) {
            return null;
        }
    }
}